import Vue from 'vue'
import Vuex from 'vuex'
import userModule from './modules/user'
import saveCartPlguin from './plugins/sava-cart'

Vue.use(Vuex)

export default new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',
  plugins: [saveCartPlguin],
  state: {
    cart: JSON.parse(localStorage.getItem('cart')) || [],
    user:[1,2,3,4]
  },
  mutations: {
    addToCart (state, payload) {
      console.log(payload)
      const has = state.cart.some(prod => prod.id === payload.id&&prod.norm === payload.norm)
      // 购物车中存在当前选购的商品，则只叠加数量，
      // 否则将当前选购商品对象添加到数组中保存
      if (has) {
        state.cart = state.cart.map(prod => {
          const copy = { ...prod }
          if (copy.id === payload.id&&copy.norm === payload.norm) {
            copy.amount += payload.amount
          }
          return copy
        })
      } else {
        state.cart.push(payload)
      }
      console.log('这是index.js'+this.state.cart)
    },
    removeFromCart (state, payload) {
      state.cart = state.cart.filter(prod => prod.id !== payload.id||prod.norm !== payload.norm)
    },
    // 修改购物车中商品数量
    modifyAmount (state, payload) {
      state.cart = state.cart.map(pord => {
        const copy = { ...pord }
        if (copy.id === payload.id) {
          copy.amount = payload.amount
        }
        return copy
      })
    }
  },
  actions: {
  },
  modules: {
    user: userModule
  },
  getters: {
    // 计算购物车商品的合计金额
    total (state) {
      return state.cart.reduce((result, prod) => (result += prod.malMobilePrice * prod.amount), 0) * 100
    }
  }
})
